package org.comiee.airwalker.enchantment;

import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentCategory;
import net.minecraft.world.level.Level;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.block.Block;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import org.jetbrains.annotations.NotNull;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static org.comiee.airwalker.block.ModBlocks.AIR_GLASS_BLOCK;

public class AirWalkerEnchantment extends Enchantment {

    /**
     * 记录临时玻璃方块 (pos → removeTick)
     */
    private static final Map<BlockPos, Long> GLASS_BLOCKS = new ConcurrentHashMap<>();
    private static long tickCounter = 0;

    public AirWalkerEnchantment() {
        super(
                Rarity.COMMON,
                EnchantmentCategory.ARMOR_FEET,
                new EquipmentSlot[]{EquipmentSlot.FEET}
        );
        // 注册事件
        MinecraftForge.EVENT_BUS.register(this);
    }

    @Override
    public int getMinCost(int level) {
        return 15;
    }

    @Override
    public int getMaxCost(int level) {
        return getMinCost(level) + 50;
    }

    @Override
    public int getMaxLevel() {
        return 3;
    }

    @Override
    public boolean checkCompatibility(@NotNull Enchantment other) {
        return super.checkCompatibility(other) &&
                !other.getDescriptionId().equals("enchantment.minecraft.depth_strider") &&
                !other.getDescriptionId().equals("enchantment.minecraft.frost_walker");
    }

    /* ---------------- 事件逻辑 ---------------- */

    @SubscribeEvent
    public void onPlayerTick(TickEvent.PlayerTickEvent event) {
        if (event.phase != TickEvent.Phase.END) return;

        Player player = event.player;
        Level level = player.level();
        if (level.isClientSide()) return;

        tickCounter++;

        int enchantLevel = player.getItemBySlot(EquipmentSlot.FEET)
                .getEnchantmentLevel(this);

        BlockPos below = player.blockPosition().below();

        if (enchantLevel > 0) {
            if (player.isCrouching()) {
                // 潜行时移除脚下的玻璃
                int radius = enchantLevel - 1;
                for (int dx = -radius; dx <= radius; dx++) {
                    for (int dz = -radius; dz <= radius; dz++) {
                        BlockPos pos = below.offset(dx, 0, dz);
                        if (level.getBlockState(pos).is(AIR_GLASS_BLOCK.get())) {
                            level.removeBlock(pos, false);
                            GLASS_BLOCKS.remove(pos);
                        }
                    }
                }
            } else {
                // 非潜行且脚下是空气 → 放置玻璃
                int radius = enchantLevel - 1;
                for (int dx = -radius; dx <= radius; dx++) {
                    for (int dz = -radius; dz <= radius; dz++) {
                        BlockPos pos = below.offset(dx, 0, dz);
                        if (level.isEmptyBlock(pos)) {
                            level.setBlock(pos, AIR_GLASS_BLOCK.get().defaultBlockState(), Block.UPDATE_CLIENTS);
                            GLASS_BLOCKS.put(pos, tickCounter + 100); // 5 秒后移除
                        }
                    }
                }
            }
        }

        // 定时清理超时的玻璃
        Iterator<Map.Entry<BlockPos, Long>> it = GLASS_BLOCKS.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<BlockPos, Long> e = it.next();
            if (tickCounter >= e.getValue()) {
                if (level.getBlockState(e.getKey()).is(AIR_GLASS_BLOCK.get())) {
                    level.removeBlock(e.getKey(), false);
                }
                it.remove();
            }
        }
    }

    /* 模组停服或需要强制清理时调用 */
    public static void clearAllGlass(ServerLevel level) {
        GLASS_BLOCKS.forEach((pos, tick) -> {
            if (level.getBlockState(pos).is(AIR_GLASS_BLOCK.get())) {
                level.removeBlock(pos, false);
            }
        });
        GLASS_BLOCKS.clear();
    }
}